/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jse;

import java.io.InputStream;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;

/**
 *
 * @author WangShuai
 */
public class STAXTest {

    public static void main(String[] args) throws XMLStreamException {
        XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        //获得类路径下的user.xml文件
        InputStream in = STAXTest.class.getResourceAsStream("/user.xml");
        XMLEventReader reader = inputFactory.createXMLEventReader(in);
        while (reader.hasNext()) {
            XMLEvent e = reader.nextEvent();
            if (e.isStartElement()) {
                StartElement se = e.asStartElement();
                if (se.getName().getLocalPart().equalsIgnoreCase("user")) {
                    String attrIdValue = se.getAttributeByName(QName.valueOf("id")).getValue(); //获得属性名称: id
                    System.out.println("userId:" + attrIdValue);
                }
            }
        }
//        XMLStreamReader reader = inputFactory.createXMLStreamReader(in);
//        while (reader.hasNext()){
//            switch (reader.getEventType())
//                {
//                case XMLStreamReader.START_ELEMENT:
//                    String name = reader.getLocalName(); //获得元素tag name: user
//                    if(name.equalsIgnoreCase("user")){
//                        String attrIdName = reader.getAttributeLocalName(0); //获得属性名称: id
//                        String attrIdValue = reader.getAttributeValue("", attrIdName); //获得ID value
//                        System.out.println("userId"+attrIdValue);
//                    }                       
//                    break;
//                case XMLStreamReader.COMMENT:
//                    String comment = reader.getText();  //获取注释文本
//                    System.out.println(comment);
//                    break;
//                }
//                reader.next();//获取下一个解析事件
//        }
    }
}
